import turtle


def drawTriangle(points, color):  # 绘制等边三角形
    t.fillcolor(color)
    t.penup()
    t.goto(points['top'])
    t.pendown()
    t.begin_fill()
    t.goto(points['left'])
    t.goto(points['right'])
    t.goto(points['top'])
    t.end_fill()


def getMid(p1, p2):
    return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)  # 取中点


def sierpinski(degree, points):
    colormap = ['blue', 'red', 'green', 'yellow', 'brown', 'purple']
    drawTriangle(points, colormap[degree])  # 等边三角形
    if degree > 0:  # 最小规模， 为 0 直接退出
        # 减小规模 getmid 边长减半
        # 调用自身，左上右次序
        sierpinski(degree - 1, {
            'left': points['left'],
            'top': getMid(points['left'], points['top']),
            'right': getMid(points['left'], points['right']),
        })
        sierpinski(degree - 1, {
            'left': getMid(points['left'], points['top']),
            'top': points['top'],
            'right': getMid(points['top'], points['right']),
        })
        sierpinski(degree - 1, {
            'left': getMid(points['left'], points['right']),
            'top': getMid(points['top'], points['right']),
            'right': points['right'],
        })


t = turtle.Turtle()
points = {  # 外轮廓三个顶点
    'left': (-200, -100),
    'top': (0, 200),
    'right': (200, -100),
}
sierpinski(5, points)  # 化degree 为5 的三角形
turtle.done()
